//
// Created by edward on 23-3-20.
//

#include "Mouse.h"
#include "Renderer.h"

bool isFirst = true;

void mouse_callback(GLFWwindow* window, double xpos, double ypos) {
    static float lastX, lastY;
    if (isFirst) {
        isFirst = false;
        lastX = xpos; lastY = ypos;
    }
    Renderer* renderer = reinterpret_cast<Renderer*>(glfwGetWindowUserPointer(window));
    /// reverse y axis
    renderer->mouseCallback(xpos - lastX, lastY - ypos);
    lastX = xpos;
    lastY = ypos;
}

void scroll_callback(GLFWwindow* window, double xoffset, double yoffset) {
    Renderer* renderer = reinterpret_cast<Renderer*>(glfwGetWindowUserPointer(window));
    renderer->setProjection(yoffset);
}

Mouse::Mouse(GLFWwindow* w)
    : isShown(false)
    , window(w)
    {
    /// register mouse scroll event callback
    glfwSetScrollCallback(window, scroll_callback);

    hide();
}

void Mouse::flip() {
    isShown = !isShown;
    if (isShown) {
        show();
    } else {
        hide();
    }
}

void Mouse::hide() {
    /// capture mouse
    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
    /// register mouse move event callback
    isFirst = true;
    glfwSetCursorPosCallback(window, mouse_callback);
}

void Mouse::show() {
    /// capture mouse
    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
    /// register mouse move event callback
    glfwSetCursorPosCallback(window, nullptr);

}
